import { ipcMain } from "electron";
import * as ipcmainHandlers from "./handlers/index.js";

// 主进程中定义（注册） ipcMain.handle方法
export const registerIcpMainHandler = () => {
  for (const key in ipcmainHandlers) {
    const ipcmainHandler = ipcmainHandlers[key];
    ipcMain.handle(key, (event, ...params) => ipcmainHandler(...params));
  }
};

// 向preload中定义暴漏（主要是主进程的ipcMain.handle方法）到web
export const exposeIcpMainHandlerForWeb = (win) => {
  win.webContents.on("did-navigate", (event, url) => {
    // 每次加载页面都注入 防止刷新或者跳转丢失
    if (url === win.webContents.getURL()) {
      win.webContents.send("ipcmainHandlerKeys", Object.keys(ipcmainHandlers));
    }
  });
};
